package com.sunday.scoremanager.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.sunday.common.adapter.MainFragmentPagerAdapter;
import com.sunday.common.common.MemberConst;
import com.sunday.common.event.EventBus;
import com.sunday.common.event.ExitApp;
import com.sunday.common.model.ResultDO;
import com.sunday.common.model.Version;
import com.sunday.common.update.UpdateDialogActivity;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.widgets.ViewPager;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.base.MyBaseActivity;
import com.sunday.scoremanager.entity.Member;
import com.sunday.scoremanager.http.ApiClient;
import com.sunday.scoremanager.push.PushIntentService;
import com.sunday.scoremanager.push.PushService;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends MyBaseActivity {

    @Bind(R.id.tab1)
    TextView tab1;
    @Bind(R.id.tab3)
    TextView tab3;
    @Bind(R.id.tab4)
    TextView tab4;
    @Bind(R.id.bottom_menu)
    LinearLayout bottomMenu;
    @Bind(R.id.content)
    ViewPager viewPager;

    private ArrayList<TextView> tabViews = new ArrayList<>();
    private ArrayList<Fragment> fragments;
    private Member member;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        checkLogin();
        initFragments();
        checkUpdate();
    }

    private void checkLogin() {
        boolean login = SharePerferenceUtils.getIns(mContext).getBoolean(Constants.IS_LOGIN, false);
        if (!login) {
            intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            member = (Member) SharePerferenceUtils.getIns(mContext).getOAuth();
            if (member != null) {
                BaseApp.getInstance().setMember(member);
            }
        }

    }

    private void initFragments() {
        tabViews.add(tab1);
       // tabViews.add(tab2);
        tabViews.add(tab3);
        tabViews.add(tab4);
        fragments = new ArrayList<>(3);
        fragments.add(IndexFragment.newInstance());
        //fragments.add(FansFragment.newInstance());
        fragments.add(IncomeFragment.newInstance());
        fragments.add(MineFragment.newInstance());
        viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setOffscreenPageLimit(3);
        viewPager.setCurrentItem(0, false);
        tabViews.get(0).setSelected(true);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < tabViews.size(); i++) {
                    tabViews.get(i).setSelected(false);
                }
                tabViews.get(position).setSelected(true);
                if (position==1){
                    try {
                        ((IncomeFragment)(fragments.get(1))).getData();
                    }catch (Exception e){
                        return;
                    }

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onRequestLocPermissionSuccessed() {
        super.onRequestLocPermissionSuccessed();
        PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
        // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), PushIntentService.class);
    }

    @OnClick({R.id.tab1,R.id.tab3, R.id.tab4})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab1:
                viewPager.setCurrentItem(0, false);
                break;
            case R.id.tab3:
                viewPager.setCurrentItem(1, false);
                break;
            case R.id.tab4:
                viewPager.setCurrentItem(2, false);
                break;
        }
    }

    @Override
    public boolean needLocationPermission() {
        return false;
    }

    @Override
    public boolean needSdCardPermission() {
        return true;
    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                EventBus.getDefault().post(new ExitApp());
                System.exit(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void checkUpdate() {
        Call<ResultDO<Version>> call = ApiClient.getApiAdapter().checkVersion(MemberConst.MANAGE, DeviceUtils.getVersionCode(getApplicationContext()));
        call.enqueue(new Callback<ResultDO<Version>>() {
            @Override
            public void onResponse(Call<ResultDO<Version>> call, Response<ResultDO<Version>> response) {
                ResultDO<Version> resultDO = response.body();
                if (isFinish){return;}
                if (resultDO != null && resultDO.getCode() == 0) {
                    final Version version = resultDO.getResult();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(mContext, UpdateDialogActivity.class);
                            intent.putExtra("version",version);
                            startActivity(intent);
                        }
                    },2000);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Version>> call, Throwable t) {

            }
        });
    }

}
